<?php 

    global $mikron;

    if($mikron->Users->CurrentUser()->user->login->value == 'sciner')
    {
        /*
        // Обновление реферальных начислений
        mysql_query('UPDATE T_USER SET `refamount` = 0 WHERE `refamount` <> 0');
        $r = mysql_query('SELECT `cabinet`, `amount` FROM T_OPERATIONS_LOG WHERE `source` = 7');
        while($row = mysql_fetch_object($r))
        {
            $amount = $row->amount;
            $user = $row->cabinet;
            mysql_query("UPDATE T_USER SET `refamount` = `refamount` + $amount WHERE `id` = $user");
            echo "$user — $amount<br />";
        }*/
    }

    $data = Array();
    
    if(isset($_REQUEST['accedit']))
    {
        $data = $_REQUEST['accedit'];
    }

    if(array_key_exists('showacc', $data) || array_key_exists('transfer', $data))
    {
        $mikron->Cache->setCache('admin_open_account_id', null);
    }
    if(!array_key_exists('openacc', $data))
    {
        if(!is_null($mikron->Cache->getCache('admin_open_account_id')))
        {
            $data['openacc'] = null;
            $data['accedid'] = $mikron->Cache->getCache('admin_open_account_id');
        }
    }

    if(array_key_exists('openacc', $data) && !is_null($data['accedid']))
    {
        $userid = (int)$data['accedid'];
        echo "{{nicewindow style=silver caption=\"Просмотр аккаунта #$userid\"}}";
        $mikron->Cache->setCache('admin_open_account_id', $userid);
        require_once(dirname(__FILE__).'/../partnerka.php');
        ?>{{/nicewindow}}<?php
         //supertuning@list.ru
    }

    if(array_key_exists('showacc', $data))
    {
        $cabid = (int)$data['accedid'];
        $cab = new T_USER($cabid);
        ?><h1>Просмотр аккаунта:</h1>
        <div style="padding: .5em; background-color: #ffe; border: 1px dotted #888; margin: 1em 0em; ">
        <?php
        echo " {{userform entityname=T_USER id=$cabid caption=&nbsp; captcha=0 returnpage=\"/?accedit[accedid]=$cabid\" processor=/}}";
        ?>
        </div>
        <div style="padding: .5em; background-color: #ffe; border: 1px dotted #888; margin: 1em 0em; ">
        <table cellspacing="0" cellpadding="1">
        <tr><td>Баланс: <td><?php echo round($cab->amount->value/100, 2); ?> руб.
        <?php if($cab->bronze->value+$cab->silver->value+$cab->gold->value+$cab->platinum->value > 0)
        {?>
        <tr><td>Бронза: <td><?php echo $cab->bronze->value; ?>
        <tr><td>Серебро: <td><?php echo $cab->silver->value; ?>
        <tr><td>Золото: <td><?php echo $cab->gold->value; ?>
        <tr><td>Платина: <td><?php echo $cab->platinum->value; ?>
        <?php } ?>
        </table>
        </div>
        <?php
        ?>{{nicewindow style=_silver caption="Посмотреть другой аккаунт:"}}<?php
    }
    elseif(array_key_exists('transfer', $data))
    {
        ?>Трансфер:<?php
        
        $all_is_ok = true;
        
        $saveditems = Array();

        $user_id = (int)$data['accedid'];
        $user = new T_USER($user_id);
        
        if(!is_object($user))
        {
            $all_is_ok = false;
        }
        else
        {
            $quantity = (int)$data['quantity'];
            $amount = $quantity * 100;
            $platinum = 0;
            $gold = 0;
            $silver = 0;
            $bronze = 0;
            $transfer = new MANUAL_TRANSFER();
            $transfer->cabinet->value = $user_id;
            $transfer->quantity->value = $amount;
            $transfer->moneytype->value = 2; // Рубли

            $referal = $user->referal->value;
            if(is_object($referal))
            {
                $foplog_referal = ChangeCabinetBalance($referal, 7, $amount * 0.1, 0, 0, 0, 0);
                $referal->refamount->value += $amount * 0.1;
                OperationLogEcp($foplog_referal, $referal);
                $foplog_referal->partner->value = $user_id;
                $saveditems[] = $referal;
                $saveditems[] = $foplog_referal;
            }

            $foplog = ChangeCabinetBalance($user, 8, $amount, $platinum, $gold, $silver, $bronze);
            OperationLogEcp($foplog, $user);

            try
            {
                $transfer->operated->value = true;
                $saveditems[] = $foplog;
                $saveditems[] = $user;
                $saveditems[] = $transfer;
                $mikron->EntityManager->Save($saveditems);
                $mikron->Users->CurrentUser()->Refresh();
            }
            catch(Exception $ex)
            {
                $all_is_ok = false;
            }
            
        }

        if($all_is_ok)
        {
            echo "<table><tr><td>{{nicewindow style=silver caption=\"Выполнено\"}}Зачисление прошло успешно.{{/nicewindow}}</td></tr></table>";
        }
        else
        {
            echo "<table><tr><td>{{nicewindow style=error caption=\"Ошибка\"}}Ошибка зачисления.{{/nicewindow}}</td></tr></table>";
        }

        ?>
        {{nicewindow style=_silver caption="Посмотреть другой аккаунт:"}}<?php
    }
    else
    {
        ?>{{nicewindow style=_silver caption="Выбери аккаунт для просмотра:"}}<?php
    }

    $email = null;
    $login = null;
    $form = new html_form('findaccount', 'post', $_SERVER['REQUEST_URI']);
    if($form->pageindex == 2)
    {
        $form->pageindex = 1;
        $email = $form->formdata['email'];
        $login = $form->formdata['login'];
        if($email==''){$email=null;}
        if($login==''){$login=null;}
    }
    $tab = new html_table(2, null, null, 4);
    $tab->newcol('E-mail:', true, false, null, null, null, 'top'); $tab->newcol(null, null, false, null, null, null, 'top'); $form->addInput(1, 'email', null, null, null, false, $email);
    $tab->newcol('Логин:', true, false, null, null, null, 'top'); $tab->newcol(null, null, false, null, null, null, 'top'); $form->addInput(1, 'login', null, null, null, false, $login);
    echo ' <font color="888888">(и/или), неизвестные символы можно заменить символом процента.</font>';
    $tab->newcol();
    $tab->newcol();
        $form->addSubmit('findaccop', 'Найти');
    $tab->end();
    $form->end();
    if(!is_null($email) || !is_null($login))
    {
        $cr = new Criteria();
        $cr->add(new Criterion('email', is_null($email)?'':"%$email%", CR_LIKE));
        $cr->add(new Criterion('login', is_null($login)?'':"%$login%", CR_LIKE, AO_OR));
        $cabs = $mikron->EntityManager->QueryDisplayNames('T_USER', null, $cr);
        if(count($cabs) < 1)
        {
            ?>Аккаунт не найден.<?php
        }
        else
        {
            $frm = new html_form("accedit", "post", "/", "return confirm('Уверен?');");
            $frm->pageindex = 1;

            ?><h1>Редактор аккаунта:</h1> <?php
            $frm->addSelectControlFromArray(1, "accedid", "Аккаунт", null, $cabs);
            $frm->addSubmit("showacc", "Редактировать");

            echo '<br /><h1>Зачислить на баланс:</h1> ';
            $frm->addInput(1, 'quantity', null, 5, 4);
            echo ' руб.';
            $frm->addSubmit("transfer", "Зачислить");

            ?><h1>Просмотр аккаунта:</h1> <?php
            $frm->addSubmit("openacc", "Посмотреть");

            $frm->end();

        }
    }
    ?>{{/nicewindow}}<?php

?>